<?php
//CURL请求的函数http_request()
//通过https 中的get 或 post
function https_request($url, $data = null){
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
    if (!empty($data)){
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
    }
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    $output = curl_exec($curl);
    curl_close($curl);
    return $output;
}

/**
 * 连接redis服务器
 * @return Redis
 */
function linkredis(){
    $redisip = C('redis_host');
    $redispasswd = C('redis_passwd');
    $redisport = C('redis_port');
    $redis = new \Redis();
    if(!$redis->connect($redisip,$redisport)){
        exit('redis数据库连接失败');
    }
    if(!$redis->auth($redispasswd)){
        exit('redis数据库认证登陆失败');
    }
    $redis->select(0);//切换到第0个库
    return $redis;
}

/**
 * 获取accesstoken
 * @param $corpid 企业号ID
 * @param $secret  管理组的凭证密钥
 * @return bool|string
 */
function tsnewsgetaccesstoken($corpid,$secret){
    $redis = linkredis();
    if(!$token = $redis->get('tsnews_accesstoken')){
        $url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={$corpid}&corpsecret={$secret}";
        $info = https_request($url);
        $accesstoken = json_decode($info,true)['access_token'];
        $redis->set('tsnews_accesstoken',$accesstoken);
        $redis->expire('tsnews_accesstoken',7100);
        return $accesstoken;
    }else{
        return $token;
    }
}

/**
 *  获取jssdk的临时票据ticket
 * @param $access_token
 * @return bool|string
 */
function tsnewsget_ticket($access_token){
    $redis = linkredis();
    if($jsapi_ticket = $redis->get('tsnews_ticket')){
        return $jsapi_ticket;
    }else{
        $url = "https://qyapi.weixin.qq.com/cgi-bin/get_jsapi_ticket?access_token={$access_token}";
        $info = https_request($url);
        $ticket = json_decode($info,true)['ticket'];
        $redis->set('tsnews_ticket',$ticket);
        $redis->expire('tsnews_ticket',7100);
        return $ticket;
    }
}

/**
 *  获取通讯录选人的临时票据ticket
 * @param $access_token
 * @return bool|string
 */
function getgroup_ticket($access_token){
    $redis = linkredis();
    if($group_ticket = $redis->get('groupid_ticket')){
        return $group_ticket;
    }else{
        $url = "https://qyapi.weixin.qq.com/cgi-bin/ticket/get?access_token={$access_token}&type=contact" ;
        $info = json_decode(https_request($url),true);
        $ticket = $info['ticket'];
        $group_id = $info['group_id'];
        $setval = $ticket .','.$group_id;
        $redis->set('groupid_ticket',$setval);
        $redis->expire('groupid_ticket',7100);
        return $setval;
    }
}
?>
